<!--
 * @Author: Seon.Hu SeonHu@126.com
 * @Date: 2023-03-09 13:32:00
 * @LastEditors: Seon.Hu SeonHu@126.com
 * @LastEditTime: 2024-02-19 15:08:07
 * @FilePath: \bg-vben\src\views\system\message\templatemessage\PayloadEditor.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <Row>
      <Tinymce
        v-model:value="tinymceContent"
        :menubar="getMenubar"
        :toolbar="getToolbar"
        :options="{ readonly: isReadonly }"
        width="100%"
        :min-height="300"
      />
    </Row>
    <Row>
      <template v-if="hasFile">
        <template v-for="item in payloadFiles" :key="item.FileName">
          <div class="mt-1">
            <Tooltip v-if="item.FileName?.length > 30" :title="item.FileName">
              <Tag
                :key="item.FileName"
                :closable="!isReadonly"
                color="blue"
                @close="handleFileDelete(item.FileName)"
              >
                <a @click="handleFileDownload(item.FileName, item.FileBase64)">{{
                  `${item.FileName.slice(0, 20)}...`
                }}</a>
              </Tag>
            </Tooltip>
            <Tag
              :key="item.FileName"
              v-else
              :closable="!isReadonly"
              color="blue"
              @close="handleFileDelete(item.FileName)"
            >
              <a @click="handleFileDownload(item.FileName, item.FileBase64)">{{ item.FileName }}</a>
            </Tag>
          </div>
        </template>
      </template>
      <template v-if="!isReadonly">
        <div class="mt-1">
          <Tooltip :title="t('component.upload.upload')">
            <CheckableTag :checked="false">
              <Upload :showUploadList="false" :multiple="true" :beforeUpload="handleFileUpload">
                <Icon icon="grommet-icons:attachment" />
              </Upload>
            </CheckableTag>
          </Tooltip>
        </div>
      </template>
    </Row>
  </div>
</template>
<script lang="ts" setup>
  import { computed, ref, watch } from 'vue';
  import { Row, Upload, Tooltip, Tag } from 'ant-design-vue';
  import { Tinymce } from '@/components/Tinymce/index';
  import Icon from '@/components/Icon/Icon.vue';

  import { useLoading } from '@/components/Loading';
  import { useI18n } from '@/hooks/web/useI18n';

  import { propTypes } from '@/utils/propTypes';
  import { getBase64WithFile } from '@/utils/common';
  import { downloadByBase64 } from '@/utils/file/download';
  import { isString } from '@/utils/is';

  const toolbar = [
    'fontfamily fontsize forecolor backcolor bold italic underline strikethrough',
    'lineheight bullist numlist alignleft aligncenter alignright outdent indent removeformat subscript superscript charmap',
    'ltr rtl table tabledelete hr pagebreak nonbreaking image media link fullscreen wordcount help',
  ];

  const CheckableTag = Tag.CheckableTag;

  defineOptions({ name: 'TemplateMessagePayloadEditor' });
  const props = defineProps({
    value: propTypes.any.def(null),
    readonly: propTypes.bool.def(false),
  });
  const emit = defineEmits(['update:value', 'change']);

  const { t } = useI18n();
  const [openFullLoading, closeFullLoading] = useLoading({});

  const getValue = computed(() => {
    const { value } = props;
    if (value) {
      if (isString(value)) {
        return JSON.parse(value);
      }
      return value;
    }
    return {};
  });
  const sourceValue = ref(getValue.value || null);
  const tinymceContent = ref<string>(getValue.value?.Content || '');
  const payloadFiles = ref<any[]>(getValue.value?.Files || []);
  //监听数据变化
  watch(
    () => props.value,
    () => {
      // console.log('props.value', props.value);
      sourceValue.value = getValue.value || null;
      tinymceContent.value = getValue.value?.Content || '';
      payloadFiles.value = getValue.value?.Files || [];
    },
  );
  watch(
    () => sourceValue.value,
    (v: any) => {
      emit('update:value', v);
      emit('change', v);
    },
  );
  watch(
    () => tinymceContent.value,
    (v: string) => {
      sourceValue.value = { ...sourceValue.value, Content: v };
    },
  );
  watch(
    () => payloadFiles.value,
    (v: any[]) => {
      sourceValue.value = { ...sourceValue.value, Files: v };
    },
  );
  const hasFile = computed(() => payloadFiles.value?.length > 0);
  /** 处理文件上传 */
  const handleFileUpload = async (file: File) => {
    openFullLoading();
    try {
      const fileBase64 = await getBase64WithFile(file);
      payloadFiles.value = [
        ...payloadFiles.value,
        { FileName: file.name, FileBase64: fileBase64.result },
      ];
    } finally {
      closeFullLoading();
    }
    return false;
  };
  /** 处理文件下载 */
  function handleFileDownload(fileName: string, fileBase64: string) {
    openFullLoading();
    try {
      if (fileName && fileBase64) {
        downloadByBase64(fileBase64, fileName);
      }
    } finally {
      closeFullLoading();
    }
  }
  /** 处理文件删除 */
  function handleFileDelete(fileName: string) {
    openFullLoading();
    try {
      if (fileName) {
        const files = payloadFiles.value || [];
        payloadFiles.value = files.filter((item) => item.FileName !== fileName);
      }
    } finally {
      closeFullLoading();
    }
  }

  //#region "是否只读"
  const isReadonly = computed(() => props.readonly);
  //#endregion
  //#region "获取富文本编辑器菜单栏设置"
  const getMenubar = computed(() => {
    const { readonly } = props;
    if (readonly) {
      return false;
    }
    return undefined;
  });
  //#endregion
  //#region "获取富文本编辑器工具栏设置"
  const getToolbar = computed(() => {
    const { readonly } = props;
    if (readonly) {
      // return 'fullscreen wordcount help';
      return false;
    }
    return toolbar;
  });
  //#endregion
</script>
